// @flow
import React from 'react'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { saveDeviceData } from 'store/modules/deviceCard'
import type { Location } from 'react-router'
import { connect } from 'react-redux'
import Condition from './Condition'

type Props = {
  location: Location,
  saveDeviceData: Function,
  history: Object,
}
type State = {
  body: any
}

const { search } = location
const paramsString = search.substring(1)
const searchParams = new URLSearchParams(paramsString)
const requestType = searchParams.get('requestType')

class SpecificGram extends React.Component {
  props: Props
  state: State
  constructor (props: Object) {
    super(props)
    this.state = {
      body: ''
    }
  }
  componentWillMount () {
    const { saveDeviceData } = this.props
    const token = searchParams.get('token')
    const deviceId = searchParams.get('deviceId')
    if (token) {
      localStorage.setItem('asset_token', token)
    }
    if (deviceId) { // 设备层
      let api = `${__SERVICE_API__}`
      if (requestType === 'wx') {
        api = `${__WXSERVICE_API__}`
      }
      universalFetch(`${api}device/devices/${deviceId}`)
        .then((res) => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          saveDeviceData(json.result)
          this.setState({
            body: <Condition />
          })
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
        })
    }
  }
  render () {
    const { body } = this.state
    return (
      <div>
        {
          body
        }
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {}
}
export default connect(mapStateToProps, { saveDeviceData })(SpecificGram)
